package com.nowcoder.community.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nowcoder.community.controller.exception.RestPageErrorException;
import com.nowcoder.community.entity.*;
import com.nowcoder.community.event.CommentEvent;
import com.nowcoder.community.mapper.MessageMapper;
import com.nowcoder.community.mapper.UserMapper;
import com.nowcoder.community.util.Constants;
import com.nowcoder.community.util.CommunityUtils;
import com.nowcoder.community.util.HostHolder;
import com.nowcoder.community.util.JsonBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MessageService {
    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    HostHolder hostHolder;

    public List<UserConversation> findConversations(int userId, Page page) {
        return messageMapper.selectConversations(userId, page.getOffset(), page.getLimit());
    }

    public long countConversations(int userId) {
        return messageMapper.countConversationsByUserId(userId);
    }

    public long countUserUnread(int userId) {
        return messageMapper.selectCount(new QueryWrapper<Message>() {{
            eq("to_id", userId);
            eq("status", Constants.MESSAGE_STATUS_UNREAD);
        }});
    }

    public UserMessageUnread getUserMessageUnread(int userId) {
        return messageMapper.countUserMessageUnread(userId);
    }

    public JsonBody sendLetter(String toName, String content) {
        User target = userMapper.selectByName(toName);
        if (target == null) {
            throw new RestPageErrorException("无效用户.");
        }
        Message message = new Message();
        message.setFromId(hostHolder.getUser().getId());
        message.setContent(content);
        message.setToId(target.getId());
        message.setStatus(Constants.MESSAGE_STATUS_UNREAD);
        message.setConversationId(CommunityUtils.getConversationId(hostHolder.getUser().getId(), target.getId()));
        messageMapper.insert(message);
        return JsonBody.ok("发送成功!");
    }

    public void sendCommentSystemNotice(SystemMessage message) {
        message.setToId(message.getToId());
        message.setStatus(Constants.MESSAGE_STATUS_UNREAD);
        messageMapper.insert(message);
    }

    public long countSystemConversations(int userId) {
        return messageMapper.countSystemConversationsByUserId(userId);
    }

    public List<SystemConversation> findSystemConversations(int userId, Page page) {
        return messageMapper.selectSystemConversations(userId, page.getOffset(), page.getLimit());
    }
}
